import { getAccount, createAccount, updateAccount, deleteAccount, updateUserPassword } from '@/api/account'
import { getAllRole } from '@/api/role'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
// 权限判断指令
import permission from '@/directive/permission/index.js'

const defaultListQuery = {
  page: 1,
  limit: 10,
  ordering: '-id',
  username: undefined,
  telephone: undefined,
  is_active: undefined,
  realname: undefined,
  role: undefined,
  faculty_code: undefined
}

const defaultTemp = {
  id: undefined,
  username: '',
  password: '',
  checkPassword: '',
  real_name: undefined,
  telephone: undefined,
  is_active: true,
  is_superuser: false
}

const defaultForm = {
  user_id: '',
  new_password: '',
  checked_new_password: ''
}

export default {
  components: { Pagination },
  directives: { permission },
  filters: {
    typeFilter(type) {
      const typeMap = {
        true: '启用',
        false: '禁用'
      }
      return typeMap[type]
    },
    statusFilter(status) {
      const statusMap = {
        true: 'success',
        false: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    var validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.temp.checkPassword !== '') {
          this.$refs.form.validateField('checkPassword')
        }
        callback()
      }
    }
    var validatePassword2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.temp.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    var validatePassword3 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.new_password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      rolesCheckedList: [],
      // 查询条件
      listQuery: Object.assign({}, defaultListQuery),
      // 账号状态
      statusList: [
        { label: '启用', value: true },
        { label: '禁用', value: false }
      ],
      roleList: [],
      dialogRoleList: [],
      temp: Object.assign({}, defaultTemp),
      accountDialogStatus: '',
      dialogFormVisible: false,
      textMap: {
        update: '编辑账号',
        create: '添加账号'
      },
      ExportVisible: false,
      createDialogRules: {
        username: [
          { required: true, message: '请输入登录账号', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
          { validator: validatePassword, trigger: 'blur' }
        ],
        checkPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
          { validator: validatePassword2, trigger: 'blur' }
        ]
      },
      updateDialogRules: {
        username: [
          { required: true, message: '请输入登录账号', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ]
      },
      resetPasswordDialogVisible: false,
      form: Object.assign({}, defaultForm),
      resetPasswordRulesList: {
        new_password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        checked_new_password: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validatePassword3, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    rulesList: function() {
      if (this.accountDialogStatus === 'create') {
        return this.createDialogRules
      } else {
        return this.updateDialogRules
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.getList()
      this.getRoles()
    },

    // 获取表格数据
    getList() {
      let list=['view_all_second_faculty','10100','10200','10300','10400','10500','10600','10700','10800','10900','11000','11100','11200','11300','11400','11500','11600','11700','11800','20100','20200','20300','20400','20500','20600','20700','20800','20900','21000','21100']
      let roles=JSON.parse(JSON.stringify(this.$store.state.user.roles))
      for (let i = 0; i < list.length; i++) {
        if(roles.indexOf(list[i])>-1){
          this.listQuery.faculty_code=list[i]
          break
        }
      }
      this.listLoading = true
      getAccount(this.listQuery).then(response => {
        this.list = response.results
        this.total = response.count

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },

    // 获取角色下拉框选择列表
    getRoles() {
      getAllRole().then(response => {
        this.roleList = response
        this.dialogRoleList = this.roleList.filter(item => {
          if (!isNaN(item['id'])) return item
        })
      })
    },

    // 搜索事件
    handleFilter() {
      if (this.listQuery.roles === '') this.listQuery.roles = undefined
      this.listQuery.page = 1
      this.getList()
    },

    // 重置搜索条件
    resetFilter() {
      this.listQuery = Object.assign({}, defaultListQuery)
    },

    // 点击删除事件
    handleDelete(row, index) {
      this.$confirm('此操作将删除该账号, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAccount(row.id).then(res => {
          this.$notify.success({
            title: '成功',
            message: res.message,
            duration: 2000
          })
          this.list.splice(index, 1)
        })
      }).catch(res => {
        this.$notify.error({
          title: '失败',
          message: res.response.data.message,
          duration: 2000
        })
      })
    },

    // 格式化, 将空的设为undefined, 为了让为空的数据不传入后台
    formatData(data) {
      for (var key in data) {
        if (data[key] === '') {
          data[key] = undefined
        }
      }
    },

    // 点击添加事件
    showCreateDialog() {
      this.temp = Object.assign({}, defaultTemp)
      this.accountDialogStatus = 'create'
      this.dialogFormVisible = true
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },

    // 进行添加
    createData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.formatData(this.temp)
          createAccount(this.temp).then(response => {
            this.list.unshift(response)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '新建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },

    // 点击修改事件
    showUpdateDialog(row) {
      this.temp = Object.assign({}, defaultTemp)
      this.accountDialogStatus = 'update'
      this.dialogFormVisible = true
      // 保存一份初始的数据, 方便提交的时候进行对比, 只更新已经修改过的字段
      this.originRowData = JSON.parse(JSON.stringify(row)) // 深拷贝, 不能Object.assign, 因为row是两层
      this.temp = Object.assign({}, row)
      this.$nextTick(function() {
        this.$refs['form'].clearValidate()
      })
    },
    // 对初始数据和将提交数据进行对比, 只提交已经修改过的字段
    diffTwoData(originRow, newRow) {
      var results = {}
      for (var key in newRow) {
        if (newRow[key] !== originRow[key]) {
          // newRow[key] = undefined
          results[key] = newRow[key]
        }
      }
      return results
    },

    // 进行修改
    updateData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          var request_data = this.diffTwoData(this.originRowData, this.temp)
          updateAccount(this.temp.id, request_data).then(response => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, response)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          }).catch((error) => {
            this.$notify({
              title: '失败',
              message: error.response.data,
              type: 'error',
              duration: 0
            })
          })
        }
      })
    },

    // 点击重置密码事件
    showResetPasswordDialog(row) {
      this.form = Object.assign({}, defaultForm)
      this.form.user_id = row.id
      this.resetPasswordDialogVisible = true
      this.$nextTick(() => {
        this.$refs['resetForm'].clearValidate()
      })
    },
    handleResetPassword() {
      this.$refs['resetForm'].validate((valid) => {
        if (valid) {
          updateUserPassword(this.form.user_id, this.form).then(response => {
            this.resetPasswordDialogVisible = false
            this.$notify({
              title: '成功',
              message: response.message,
              type: 'success',
              duration: 2000
            })
          }).catch((error) => {
            this.$notify({
              title: '错误',
              message: error.response.data,
              type: 'error',
              duration: 0
            })
          })
        }
      })
    }

  }
}
